<?php

/**
 * 三西大同关务订单对接
 * @author chenshubo
 */
namespace App\Service\VendorClient\ShopSanXiDaTong;

use App\Service\BaseService;
use Service\AppService\IdService;
use App\Model\PssModel\ServiceConfig;
use App\Service\TaskServer\TaskWorker;
use App\Service\Code\Normal;

class ShopSanXiDaTongApiClient extends BaseService
{
    private $config;
    protected $methods = [
        'AddOrder'          => '/api/mf/airymall/order/AddOrder',
        'InvtStatusQuery'   => '/api/mf/airymall/order/InvtStatusQuery'
    ];
    
    public function __construct( $apiBody = [] )
    {
        $this->config = $apiBody;
    }
    
    /**
     * 创建订单
     */
    public function createOrder( $params = [] )
    {
        $orderInfo      = $params['supplierOrder'];
        $orderItem      = $params['orderGoods'];
        $order          = $params['order'];
        $binfo          = $params['binfo'];
        
        //支付流水号
        $pay_sn         = $order['paySerial'] ?? $orderInfo['pay_sn'];
        //运费
        $deliver_money  = $orderInfo['deliver_money'];
        //优惠
        $discount_money = $orderInfo['discount_money'] < 0 ? - $orderInfo['discount_money'] : $orderInfo['discount_money'] ;
        //下单支付的时候支付信息
        $apply_extends  = @json_decode($orderInfo['apply_extends'],true);
        //支付时间
        $pay_time       = date('Y-m-d H:i:s',$orderInfo['pay_time']);
        //支付流水号
        $pay_sn         = $order['paySerial'] ?? $orderInfo['pay_sn'];
        $order_sn       = $orderInfo['supplier_dsn'];
        
        //组装商品数据列表
        $goodsList          = [];
        $goodsTotalMoney    = 0;
        foreach ($orderItem as $key =>  & $item )
        {
            $price              = $item['price'];
            $spec_num           = $item['spec_num'];
            $quantity           = $item['quantity'];
            $supplier_skucode   = $item['supplier_skucode'];
            $singleGoodsPrice   = bcdiv((string)$price,(string)$spec_num,2);
            $buyNum             = bcmul((string)$spec_num,(string)$quantity);
            
            //单个运费
            if( $key == 0 ) {
                $singleDeliveryMoney = bcdiv((string)$deliver_money,(string)$buyNum,2);
                $singleGoodsPrice = bcadd((string)$singleDeliveryMoney,(string)$singleGoodsPrice,2);
            }
            
            //单个商品总价
            $goodsTotalPrice    = bcmul((string)$buyNum,(string)$singleGoodsPrice,2);
            $goodsInfo = [
                'RecordCode'    => $supplier_skucode,
                'BuyQuantity'   => (string)$buyNum,
                'BuyPrice'      => (string)( bcmul((string)$singleGoodsPrice,'100')),
                'Rank'          => $key + 1,
            ];
            $goodsList[] = $goodsInfo;
            $goodsTotalMoney = bcadd((string)$goodsTotalMoney,(string)$goodsTotalPrice,2);
        }
        
        //订单总价（商品保税价格 + 运费）
        $deliver_money          = 0;
        $totalMoney             = bcadd((string)$goodsTotalMoney, (string)$deliver_money,2);
        
        //订单优惠金额
        $real_total_money       = $orderInfo['real_total_money'];
        $discount_money         = bcsub((string)$totalMoney,(string)$real_total_money,2);
        
        //判断支付方式是否存在
        $payCommanyCode = $apply_extends['payCommanyCode']??'';
        $PayCompanyCode = $order['payCommanyCode'] ?? $payCommanyCode ;
        $pay_value = ServiceConfig::instance()->getConfigByEventsValue('shopsanxidatong', ServiceConfig::TYPE_PAY, $PayCompanyCode);
        if( empty($pay_value) ) {
            return Normal::returnCode(Normal::FAIL,"支付公司编码：【{$PayCompanyCode}】未映射，请联系管理员处理");
        }
        
        $payDecarleRequest = $order['payDecarleRequest'] ?? $orderInfo['apply_request'];
        $payDecarleResponse = $order['payDecarleResponse'] ?? $orderInfo['apply_response'];
        
        //创建订单数据
        $data = [
            'OrderNo'           => $orderInfo['supplier_dsn'],
            'PayNo'             => $pay_sn,
            'PostalPrice'       => bcmul((string)$deliver_money,'100'),
            'OrderPrice'        => bcmul((string)$totalMoney,'100'),
            'ExpressCode'       => $this->config['ExpressCode'],
            'TrafMode'          => $this->config['TrafMode'],//保税仓库
            'PackNo'            => 1,
            'InsureFee'         => 0,
            'ConsigneeName'     => $orderInfo['receive_name'],
            'ConsigneeNumber'   => $orderInfo['recveive_phone'],
            'BuyerName'         => $orderInfo['buyer_realname'],
            'IdCard'            => $orderInfo['buyer_idcard'],
            'DetailedAddres'    => implode("",[
                $orderInfo['province'],
                $orderInfo['city'],
                $orderInfo['district'],
                $orderInfo['receive_address']
            ]),
            'OrderTime'         => date("YmdHis",$orderInfo['cd']),
            'PayDate'           => date("YmdHis",strtotime($pay_time)),
            'WarehouseCode'     => $this->config['WarehouseCode'],
            'OrderDesc'         => $orderInfo['order_remark'],
            'AdminMessage'      => $orderInfo['order_remark'],
            'OrderItems'        => $goodsList,
            'MallCusCode'       => $this->config['MallCusCode'],
            'PayCusCode'        => $PayCompanyCode,
            'InventoryCusCode'  => $this->config['InventoryCusCode'],
            'PortCode'          => $this->config['PortCode'],
            'BusinessMode'      => $this->config['BusinessMode'],
            'AddresserName'     => $this->config['AddresserName'],
            'AddresserPhone'    => $this->config['AddresserPhone'],
            'PayType'           => $pay_value,
            'PayChannelType'    => $this->config['PayChannelType'],//支付通道类型
            'InventoryPltCode'  => $this->config['InventoryCusCode'],
            'SellWebSite'       => $this->config['SellWebSite'],
            'ExpressType'       => 1,
            'BindCodeMode'      => 1,
            'ExpressNo'         => '',
            'BuyerTelePhone'    => $orderInfo['buyer_phone'],
            'InitalRequest'     => $payDecarleRequest,
            'InitalResponse'    => $payDecarleResponse,
            'RecpAccount'       => $orderInfo['buyer_phone']
        ];
        $requestParam = [
            'method'    => 'AddOrder',
            'data'      => $data,
        ];
        return $this->execute($requestParam);
    }

    /**
     * 查询清关状态
     * @param string $order_sn
     */
    public function queryOrderClearanceByOrderSn( string $order_sn )
    {
        $data = [
            'OrderNo'   => $order_sn
        ];
        $requestParam = [
            'method'    => 'InvtStatusQuery',
            'data'      => $data,
        ];
        return $this->execute($requestParam);
    }
    
    
    /**
     * 获取sign参数
     */
    private function getSign( $param = [] )
    {
        $str = $this->config['key'].$param['date'].$param['interfacename'].$param['content'];
        return strtoupper(md5($str));
    }

    /**
     * CURL请求
     * @param $params
     * @return mixed
     */
    public function execute( $param = [] )
    {
        $method = $param['method'];
        $data   = $param['data'];
        $data  = [
            'content'       => json_encode($data),
            'interfacename' => $param['method'],
            'date'          => date('Y-m-d')
        ];
        $token   = $this->getSign($data);
        $header = [
            "Content-Type: application/json",
            "Accept:application/json",
            "interfacename:{$method}",
            "token:{$token}",
            "orgCode:{$this->config['orgCode']}"
        ];
        $url = $this->config['baseurl'].$this->methods[$method];
        $parameter = [
            [
                'tag'       => 'shopsanxidatong_'.$method,
                'uid'       => IdService::instance()->getOtherID(),
                'url'       => $url,
                'data'      => $param['data'],
                'method'    => 'post',
                'format'    => 'json',
                'header'    => $header,
            ],
        ];
        $resTask        = TaskWorker::instance()->addTask($parameter);
        $resTask        = current($resTask);
        $resHttp        = json_decode($resTask['response']['result'], true);
        if( isset($resHttp['Code']) && $resHttp['Code'] == '0000' ) {
            return Normal::returnCode(Normal::SUC,"创建订单成功",$resHttp);
        }
        
        $Message = $resHttp['Message'] ?? '请求失败';
        return Normal::returnCode(Normal::FAIL,$Message);
    }
}
